#include "move_sprite_fx.h"

#include "util/timer.h"				// log
#include "util/log.h"				// log
#include "util/common_macros.h"		// macros
#include "util/mmgr.h"		    

#include <math.h>

using namespace vfx;

MoveSpriteSFX::MoveSpriteSFX(EffectMan*	pParent, const std::string& Image, int	MaxCount, bool Additive) :
	SFXSet(pParent),
	m_MaxCount(0),
	m_CurrentCount(0),
	m_SpriteA(NULL),
	m_Additive(Additive)
{
	m_MaxCount = MaxCount;
	m_SpriteA = new MoveSprite[m_MaxCount];
	for (int i=0; i<MaxCount; i++)
	{
		m_SpriteA[i].Sprite.Create(Image);
		m_SpriteA[i].Active = false;
	}
	m_SpriteA[0].Sprite.GetScreenSize(m_SpriteSize);
}

MoveSpriteSFX::~MoveSpriteSFX()
{
	UTIL_SAFE_DELETEA(m_SpriteA);
}

void					MoveSpriteSFX::Render(const math::Vec2& Offset, float Scale)
{
	if (m_CurrentCount <=0) return;
	for (int i=0; i<m_MaxCount; i++)
	{
		if (m_SpriteA[i].Active)	
		{
			m_SpriteA[i].Sprite.m_Pos = (m_SpriteA[i].Pos - Offset) * Scale;
			m_SpriteA[i].Sprite.m_Size = (m_SpriteSize * Scale);
			m_SpriteA[i].Sprite.RenderRotated();
		}
	}
}

void					MoveSpriteSFX::Tick(float dt)
{
	if (m_CurrentCount <=0) return;
	for (int i=0; i<m_MaxCount; i++)
	{
		if (m_SpriteA[i].Active)	
		{

			m_SpriteA[i].Progress.Tick(dt);
			if (m_SpriteA[i].Progress.IsReady())
			{
				m_SpriteA[i].Active = false;
				m_CurrentCount--;
			} else
			{
				m_SpriteA[i].Sprite.Tick(dt);

				float	Prog = m_SpriteA[i].Progress.GetProgress();
				float	SinOffset = (0.5f+sinf(Prog * 3.14f)) * (0.5f*m_SpriteA[i].SineAmp);
				float	SinSize = 0.5f + (0.5f * sinf(Prog * 3.14f) * m_SpriteA[i].SizeAmp);
				math::Vec2	Delta = m_SpriteA[i].To - m_SpriteA[i].From;
				m_SpriteA[i].Pos = m_SpriteA[i].From + (Delta*Prog) + math::Vec2(Delta.y * SinOffset, -Delta.x * SinOffset);
				m_SpriteA[i].Sprite.m_Size = m_SpriteA[i].Size * SinSize;
			}
		}
	}
}


void					MoveSpriteSFX::AddSprite(const math::Vec2& Pos, const math::Vec2& To, float Time, float SineAmp,float  SizeAmp , COLOR Color )
{
	if (m_CurrentCount == m_MaxCount) return;	// cannot

	for (int i=0; i<m_MaxCount; i++)
	{
		if (!m_SpriteA[i].Active)
		{
			m_SpriteA[i].Active		= true;
			m_SpriteA[i].Pos		= m_SpriteA[i].From = Pos;
			m_SpriteA[i].To			= To;
			m_SpriteA[i].Color		= Color;
			m_SpriteA[i].SineAmp	= SineAmp;
			m_SpriteA[i].SizeAmp	= SizeAmp;
			m_SpriteA[i].Progress.SetLimit(Time);
			m_SpriteA[i].Sprite.GetScreenSize(m_SpriteA[i].Size);
			m_SpriteA[i].Sprite.Setup(Pos, m_SpriteA[i].Size, 0, 1, Color);
			m_CurrentCount++;
			return;
		}
	}
}

void					MoveSpriteSFX::GetSpriteSize(math::Vec2& Size)
{
	m_SpriteA[0].Sprite.GetScreenSize(Size);
}
